//
//  FoundViewController.m
//  BabyBedtimeStory
//
//  Created by qianfeng on 15-6-19.
//  Copyright (c) 2015年 张鹏毅. All rights reserved.
//

#import "FoundViewController.h"
#import "JHRefresh.h"
#import "AFNetworking.h"
#import "StoryModel.h"
#import "FountCell.h"
#import "HeaderView.h"
#import "FootView.h"
#import "DetailViewController.h"

#define kScreenSize [UIScreen mainScreen].bounds.size
@interface FoundViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
{
    AFHTTPRequestOperationManager *_manager;
}
@property (nonatomic,strong) UICollectionView *collectView;
@property (nonatomic,strong) NSMutableArray *dataArr;
@property (nonatomic,strong) NSMutableArray *arrData;
@end

@implementation FoundViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isRefreshing = NO;
    [self creatCollectView];
    [self creatAf];
    [self StartDownloadingData];
    [self beginRefreshing];
}

#pragma mark - 创建collectView
-(void)creatCollectView{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.dataArr = [[NSMutableArray alloc]init];
    self.arrData = [[NSMutableArray alloc]init];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(kScreenSize.width/4+6, kScreenSize.width/4+6);
    layout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    layout.minimumLineSpacing = 45;
    layout.headerReferenceSize = CGSizeMake(0, 50);
    layout.footerReferenceSize = CGSizeMake(0, 50);
    self.collectView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, kScreenSize.width, kScreenSize.height-64-49) collectionViewLayout:layout];
    self.collectView.backgroundColor = [UIColor whiteColor];
    self.collectView.dataSource = self;
    self.collectView.delegate = self;
    [self.collectView registerClass:[FountCell class] forCellWithReuseIdentifier:@"FountCell"];
    [self.collectView registerClass:[HeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];
    [self.collectView registerClass:[FootView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"Footer"];
    [self.view addSubview:self.collectView];
}

#pragma mark - 创建下载
-(void)creatAf{
    _manager =[AFHTTPRequestOperationManager manager];
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
}

#pragma mark - 开始下载
-(void)StartDownloadingData{
    __weak typeof(self) weakSelf = self;
    
    BOOL isExist = [[NSFileManager defaultManager]fileExistsAtPath:[LZXHelper getFullPathWithMyCacheFile:kSecond]];
    BOOL isTimeOut = [LZXHelper isTimeOutFile:[LZXHelper getFullPathWithMyCacheFile:kSecond] time:20*60*60];
    if (self.isRefreshing == NO&&isExist == YES&&isTimeOut == NO) {
        NSData *data = [NSData dataWithContentsOfFile:[LZXHelper getFullPathWithMyCacheFile:kSecond]];
        [self ParsingWithData:data];
    }else{
        self.isRefreshing = YES;
        [_manager GET:kSecond parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (responseObject) {
                NSData *data = (NSData *)responseObject;
                NSString *filePath = [LZXHelper getFullPathWithMyCacheFile:kSecond];
                [data writeToFile:filePath atomically:YES];
                [weakSelf ParsingWithData:data];
                [weakSelf stopRefreshing];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [weakSelf stopRefreshing];
        }];
    }
    
}

#pragma mark - 数据解析
-(void)ParsingWithData:(NSData *)data{
    [self.arrData removeAllObjects];
    [self.dataArr removeAllObjects];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSArray *arr = dict[@"data"];
    for (NSDictionary *dictArr in arr) {
        NSDictionary *dictArray = dictArr[@"column"];
        StoryModel *model = [[StoryModel alloc]init];
        [model setValuesForKeysWithDictionary:dictArray];
        [self.arrData addObject:model];
        NSArray *arr1 = dictArr[@"data_list"];
        NSMutableArray *arr6 = [[NSMutableArray alloc]init];
        for (NSDictionary *dictArr in arr1) {
            
            StoryModel *model = [[StoryModel alloc]init];
            [model setValuesForKeysWithDictionary:dictArr];
            [arr6 addObject:model];
        }
        [self.dataArr addObject:arr6];
    }
    [self.collectView reloadData];
}

#pragma mark - collectView协议
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataArr.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.dataArr[section] count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    FountCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FountCell" forIndexPath:indexPath];
    StoryModel *model = self.dataArr[indexPath.section][indexPath.row];
    [cell showWithModel:model];
    return cell;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        HeaderView *cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Header" forIndexPath:indexPath];
        StoryModel *model = self.arrData[indexPath.section];
        [cell showWithModel:model];
        return cell;
    }else{
        FootView *cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Footer" forIndexPath:indexPath];
        return cell;
    }
    
}

#pragma mark - 选中cell
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    StoryModel *model = self.dataArr[indexPath.section][indexPath.row];
    DetailViewController *vc = [[DetailViewController alloc]init];
    vc.id = model.item_value;
    vc.title = model.sub_title;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)beginRefreshing{
    __weak typeof(self) weakSelf =self;
    if (self.isRefreshing) {
        return;
    }
    [self.collectView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        weakSelf.isRefreshing = YES;
        [weakSelf StartDownloadingData];
    }];
}

-(void)stopRefreshing{
    if (self.isRefreshing) {
        self.isRefreshing = NO;
        [self.collectView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
